/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elderberryni2.datareader;

import elderberryni2.interfaces.IDataReadable;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 *
 * @author warringer
 */
public class NetworkUDPReader implements IDataReadable {

    private DatagramSocket theSocket = null;
    private int serverPort = 54345;
    private DatagramPacket theReceivedPacket;
    private byte[] inBuffer = new byte[1000];
    
    public NetworkUDPReader(int port) {
        serverPort = port;
        try {
            theSocket = new DatagramSocket(serverPort);
            System.out.println("Client socket created");
	}catch (SocketException ExceSocket)
	{
            System.out.println("Socket creation error  : "+ExceSocket.getMessage());
        }
    }
    
    @Override
    public String getData() {
        String output = null;
        try {
            theReceivedPacket = new DatagramPacket(inBuffer, inBuffer.length);
            theSocket.receive(theReceivedPacket);
            // the server response is...
            output = new String(theReceivedPacket.getData(), 0, theReceivedPacket.getLength());
	} catch (IOException ExceIO)
	{
            System.out.println("Client getting data error : "+ExceIO.getMessage());
        }
        return output;
    }

    @Override
    public void pauseData() {
    }

    @Override
    public void unpauseData() {
    }

    @Override
    public void close() {
        theSocket.close();
    }
    
}
